package com.lifegame.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.TimeUtils;
import com.sun.org.apache.xpath.internal.operations.Or;

import java.sql.Time;

public class LifeGame extends ApplicationAdapter{
	int n=100;
	int cell[][]=new int[100][100];
	int nex[][]=new int[100][100];
	long lastTime;
	private Pixmap pt1;
	private Pixmap pt2;
	private Pixmap pt3;
	private Texture ptt1;
	private Texture ptt2;
	private Texture ptt3;
	private OrthographicCamera camera;
	private SpriteBatch batch;
	public int get(int x,int y){
		if(x<0||y<0||x>=n||y>=n) return 0;
		return cell[x][y];
	}
	public void initCell(){
		for(int i=49;i<=50;i++)
			for(int j=49;j<=50;j++)
				cell[i][j]=1;
	}
	public void draw(){
		batch.setProjectionMatrix(camera.combined);
		batch.begin();
		int x=0,y=0;
		for(int i=0;i<n;i++,y+=8) {
			if(i%2==0) x=4;
			else x=8;
			for (int j=0;j<n;j++,x+=8){
				if (cell[i][j] == 0) continue;
				batch.draw(ptt1,x-4,y+8);
				batch.draw(ptt2,x-4,y+3);
				batch.draw(ptt3,x-4,y+11);
			}
		}
		batch.end();
	}
	@Override
	public void create(){
		camera=new OrthographicCamera();
		camera.setToOrtho(false,800,800);
		batch=new SpriteBatch();
		pt1=new Pixmap(8,5, Pixmap.Format.RGBA8888);
		pt2=new Pixmap(8,5, Pixmap.Format.RGBA8888);
		pt3=new Pixmap(8,5, Pixmap.Format.RGBA8888);
		pt1.setColor(0,0,0,0);
		pt2.setColor(0,0,0,0);
		pt3.setColor(0,0,0,0);
		pt1.fill();pt2.fill();pt3.fill();
		pt1.setColor(1,1,1,1);
		pt2.setColor(1,1,1,1);
		pt3.setColor(1,1,1,1);
		pt1.fillRectangle(0,0,8,5);
		pt2.fillTriangle(0,0,8,0,4,3);
		pt3.fillTriangle(0,3,4,0,8,3);
		ptt1=new Texture(pt1);
		ptt2=new Texture(pt2);
		ptt3=new Texture(pt3);
		initCell();
		draw();
	}
	@Override
	public void render(){
		draw();
		ScreenUtils.clear(0,0,0.2f,1);
		camera.update();
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++){
				int env=get(i-1,j)+get(i+1,j)+get(i,j-1)+get(i,j+1);
				if(i%2==0) env+=get(i-1,j+1)+get(i+1,j+1);
				else env+=get(i-1,j-1)+get(i+1,j-1);
				if(env<2||env>3) nex[i][j]=0;
				else nex[i][j]=1;
			}
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++)
				cell[i][j]=nex[i][j];
		draw();
		lastTime=TimeUtils.nanoTime();
	}
}
